<template>
  <a-modal width="650px" :visible="visible" :mask-closable="false" :title="props.title" @cancel="close" unmount-on-close>
    <div class="mb-2">
      请选择需要导出的费项：
      <a-checkbox :model-value="checkedAll" :indeterminate="indeterminate" @change="handleChangeAll">全选</a-checkbox>
    </div>
    <a-scrollbar style="max-height: 63vh; overflow-y: auto">
      <div v-for="(item, index) in orderCheckArr" :key="index">
        <a-checkbox
          class="block mb-2"
          :model-value="item.checkAll"
          :indeterminate="item.indeterminate"
          @change="handleChangeItemAll($event, item)"
        >
          <span class="font-medium">{{ item.feeCategoryName }}</span>
        </a-checkbox>
        <a-checkbox-group v-model="data" @change="handleChange($event, item)">
          <a-checkbox :value="check.itemValue" :key="_index" v-for="(check, _index) in item.childrenList">{{ check.itemName }}</a-checkbox>
        </a-checkbox-group>
        <a-divider v-if="index != orderCheckArr.length - 1" />
      </div>
    </a-scrollbar>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" :loading="okLoading" @click="ok">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref } from 'vue'
  import { getSelectAllItemName } from '@/api/order/sOrder'
  import { useExport } from '@/hooks/list'
  const props = defineProps({
    title: {
      type: String,
      default: '',
    },
    fetch: {
      type: String,
      default: '',
    },
  })

  const emits = defineEmits(['ok'])

  const visible = ref(false)
  // 半选状态
  const indeterminate = ref(false)
  // 是否全选
  const checkedAll = ref(false)
  // 选中数组
  const data = ref([])
  // 源数据
  const orderCheckArr = ref([])
  // 所以选项值拉平
  let checkAllData = []
  // loading状态
  const okLoading = ref(false)

  const queryParam = ref({})
  // group全选
  const handleChangeItemAll = (value, item) => {
    item.checkAll = value
    item.indeterminate = false
    let checkData = item.childrenList.map((it) => it.itemValue)
    let newData = value ? data.value.concat(checkData) : data.value.filter((it) => !checkData.includes(it))
    data.value = [...new Set(newData)]
    checkedAll.value = data.value.length === checkAllData.length
    indeterminate.value = data.value.length !== 0 && data.value.length !== checkAllData.length
  }
  // 全选
  const handleChangeAll = (value) => {
    indeterminate.value = false
    checkedAll.value = value
    orderCheckArr.value.map((it) => ((it.checkAll = value), (it.indeterminate = false)))
    data.value = value ? [...checkAllData] : []
  }
  // 单个选择
  const handleChange = (value, item) => {
    checkedAll.value = value.length === checkAllData.length
    indeterminate.value = value.length !== 0 && value.length !== checkAllData.length
    let checkData = item.childrenList.map((it) => it.itemValue)
    let values = value.filter((it) => checkData.includes(it))
    item.checkAll = checkData.length === values.length
    item.indeterminate = values.length !== 0 && checkData.length !== values.length
  }

  // 拆分导出数据
  const formatExportData = () => {
    const formattedData = data.value.map((item) => {
      const arr = item.split(',')
      const feeCategory = arr[0]
      const itemName = arr[1]
      return {
        feeCategory,
        itemName,
      }
    })
    return formattedData
  }

  const ok = () => {
    okLoading.value = true
    queryParam.value.exportItemList = formatExportData()
    useExport(props.fetch, queryParam.value).finally(() => {
      close()
      emits('ok')
      sessionStorage.setItem('shortOrderSelectRowKeys', JSON.stringify(data.value))
    })
  }
  const open = (param) => {
    queryParam.value = param
    getSelectAllItemName().then((res) => {
      orderCheckArr.value = handleCheckData(res.result)
      checkAllData = orderCheckArr.value.map((it) => it.childrenList.map((_it) => _it.itemValue)).flat()
      visible.value = true
      // 处理已选中的数据
      let checkedData = sessionStorage.getItem('shortOrderSelectRowKeys')
      data.value = checkedData ? JSON.parse(checkedData) : []
      orderCheckArr.value.forEach((item) => {
        let checkData = item.childrenList.map((it) => it.itemValue)
        let values = data.value.filter((it) => checkData.includes(it))
        item.checkAll = checkData.length === values.length
        item.indeterminate = values.length !== 0 && checkData.length !== values.length
      })
      checkedAll.value = data.value.length === checkAllData.length
      indeterminate.value = data.value.length !== 0 && data.value.length !== checkAllData.length
    })
  }
  // 处理数据-添加checkAll/check/itemValue字段
  const handleCheckData = (data) => {
    const processedData = data.map((item) => {
      const newItem = { ...item, checkAll: false, indeterminate: false, itemValue: item.feeCategory + ',' + item.feeCategoryName }
      if (newItem.childrenList && Array.isArray(newItem.childrenList)) {
        newItem.childrenList = newItem.childrenList.map((child) => ({
          ...child,
          check: false,
          itemValue: child.feeCategory + ',' + child.itemName,
        }))
      }

      return newItem
    })

    return processedData
  }

  const close = () => {
    okLoading.value = false
    visible.value = false
  }
  defineExpose({
    open,
  })
</script>
